<?php
/**
 * Holds class Cache
 *
 * @author daantimmer
 *
 * @package Library
 * @subpackage Cache
 */

/**
 * Wrapper class around different methods of caching.
 *
 * This class is used as a wrapper around different sorts of
 * caching (File/DB/Memory). Currently only the File cache is fully written.
 *
 * The constructor accepts a Cache_Container. This container is either a file-cache,
 * db-cache or memory-cache container.
 *
 * @see Cache_Container
 *
 * @author daantimmer
 */
class Cache{

	/**
	 * @var Cache_Container
	 */
	private $container;

	/**
	 * @param Cache_Container $container
	 * @return void
	 */
	public function __construct(Cache_Container $container){
		$this->container = $container;
	}

	/**
	 * Stores $data for $timeout of seconds using $key
	 *
	 * @param Cache_Key $key
	 * @param mixed $data arbitrary data
	 * @param integer $timeout timeout in seconds
	 * @param boolean $encrypt unsupported at the moment. base64_encode is not binary safe
	 * @return void
	 */
	public function store(Cache_Key $key,$data,$timeout,$encrypt = true){
		$data = serialize($data);
//		if($encrypt === true)
//			$data = @(base64_encode(base64_encode($data).base64_encode(md5($key->password))));
		$this->container->write($key,$data,$timeout);
	}

	/**
	 * Retrieves data from $key
	 *
	 * @param Cache_Key $key
	 * @param boolean $encrypted unsupported at the moment. base64_encode is not binary safe
	 * @return mixed
	 */
	public function load(Cache_Key $key,$encrypted = true){
		$data = $this->container->read($key);
		return unserialize($data);
	}

	/**
	 * Checks if $key is set in the current cache
	 *
	 * @param Cache_Key $key
	 * @return boolean
	 */
	public function check(Cache_Key $key){
		return $this->container->check($key);
	}

	/**
	 * Returns statistics of the current cache
	 *
	 * @return mixed
	 */
	public function statistics(){
		return $this->container->getStatistics();
	}

	/**
	 * Clears the cache
	 *
	 * @return boolean
	 */
	public function clear(){
		return $this->container->clear();
	}

	/**
	 * Used to 'touch' cached data. Resetting the timeout.
	 *
	 * @ignore unimplemented
	 * @param Cache_Key $key
	 * @return void
	 */
	public function touch(Cache_Key $key){
		throw new BadMethodCallException("NotImplemented");
	}

	/**
	 * Creates a key from an arbitrary amount of params. Any type of param can be given.
	 *
	 * This funcitno will first serialize the array array_slize(func_get_args(),1)
	 * Afte that it will use sha1 to create a key
	 *
	 * $password can be left null as it is currently unsupported due to base64_encode not being binary safe
	 *
	 * @param string $password
	 * @param mixed [...]
	 * @return Cache_Key
	 */
	public function createKey($password = null){
		$args = func_get_args();
		return new Cache_Key(sha1($password),sha1(serialize(array_slice($args,1))));
	}
}